package com.example.braden.answergame.common.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.util.Log;

import com.example.braden.answergame.R;
import com.example.braden.answergame.base.BaseApplication;
import com.example.braden.answergame.common.LogUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by braden on 2018/1/12.
 */

public class MediaUtil implements SoundPool.OnLoadCompleteListener {

    private static Context mContext;
    private MediaPlayer player = null;

    private MediaUtil() {
    }

    public static MediaUtil getInstance(Context context) {
        mContext = context;
        return MediaUtilHolder.instance;
    }

    private static final class MediaUtilHolder {
        static MediaUtil instance = new MediaUtil();
    }

    public void playForMediaPlayer(int res) {
        if (player == null) {
            player = MediaPlayer.create(mContext, res);
        }
        player.seekTo(0);
        player.start();
    }

    /**
     * 释放MediaPlayer
     */
    public void releaseMedia() {
        try {
            if (null != player) {
                player.stop();
                player.reset();
                player.release();
                player = null;
            }
            if (null != mSoundPool) {
                mSoundPool.setOnLoadCompleteListener(null);
                mSoundPool.release();
            }

            if (null != mAlreadyLoadSound) {
                mAlreadyLoadSound.clear();
            }
            mContext = null;
            mSoundPool = null;
            mAlreadyLoadSound = null;
        } catch (Exception ex) {
            LogUtils.e("ex:" + ex.toString());
        }

    }

    public void playeSmallVoice(int rawId) {
        if (CommonUtil.isAppIsInBackground(mContext)) return;
        ensureInit();
        Integer soundId = mAlreadyLoadSound.get(rawId);
        if (soundId == null) {
            soundId = mSoundPool.load(mContext.getApplicationContext(), rawId, 1);
            mAlreadyLoadSound.put(rawId, soundId);
        } else {
            mSoundPool.play(soundId, 1, 1, 1, 0, 1);
        }
    }

    //==========================================================
    private SoundPool mSoundPool;
    private Map<Integer, Integer> mAlreadyLoadSound;

    private void ensureInit() {
        if (null == mSoundPool) {
            mSoundPool = new SoundPool(6, AudioManager.STREAM_MUSIC, 0);
            mSoundPool.setOnLoadCompleteListener(this);
        }
        if (null == mAlreadyLoadSound) {
            mAlreadyLoadSound = new HashMap<>();
        }
    }

    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
        Log.d("MediaUtil", "onLoadComplete soundId = " + sampleId);
        soundPool.play(sampleId, 1, 1, 1, 0, 1);
    }
}
